package com.springboot.frame.sso.cas;

import net.unicon.cas.client.configuration.EnableCasClient;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static org.jasig.cas.client.util.AbstractCasFilter.CONST_CAS_ASSERTION;

// 启用cas
@EnableCasClient
@SpringBootApplication
public class Client001Application {

    @Controller
    public class SsoC1Controller {
        @Autowired
        private CasProperties casProperties;

        @RequestMapping("/sso-c1/")
        public String hello(HttpSession session) {
            Assertion assertion = (Assertion) session.getAttribute(CONST_CAS_ASSERTION);
            AttributePrincipal principal = assertion.getPrincipal();
            String loginName = principal.getName();
            return String.format("sso-c1 %s hello word!", loginName);
        }

        /**
         * 退出 后自动重定向自定义接口
         *
         * @param request
         * @return
         */
        @RequestMapping("/system/logout")
        public String logout1(HttpServletRequest request) {
            HttpSession session = request.getSession();
            session.invalidate();
            return String.format("redirect:%s?service=%s/system/logoutSuccess", casProperties.getServerUrlPrefix().concat("/logout"), casProperties.getClientHostUrl());
        }

        /**
         * 退出成功页
         *
         * @return
         */
        @RequestMapping("/system/logoutSuccess")
        @ResponseBody
        public String logoutSuccess() {
            return "sso-c1 成功退出！";
        }
    }


    public static void main(String[] args) {
        SpringApplication.run(Client001Application.class, args);
    }
}
